package com.bruce.starts.demo.thread.lock;

import java.util.concurrent.locks.ReentrantLock;

public class Buffer {
    private ReentrantLock lock = new ReentrantLock();
    public void write(){
        lock.lock();
        try {
            long startTime = System.currentTimeMillis();
            System.out.println("开始往buffer写入数据....");
            for(;;){
                if(System.currentTimeMillis()-startTime>3000){
                    break;
                }
            }
            System.out.println("终于写完了");
        }finally {
            lock.unlock();
        }
    }

    public void read() throws InterruptedException {
        lock.lockInterruptibly();// 注意这里，可以响应中断
        try {
            System.out.println("从这个buff读数据");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        final Writer writer = new Writer(buffer);
        final Reader reader = new Reader(buffer);
        writer.start();
        reader.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                long startTime = System.currentTimeMillis();
                for(;;){
                    if(System.currentTimeMillis()-startTime>5000){
                        System.out.println("不等了，尝试终止");
                        reader.interrupt();
                        break;
                    }
                }
            }
        }).start();
    }
}
